#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/esb/management/commands/sync_buffet_components.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.

init buffet component to db
"""
from django.core.management.base import BaseCommand
from esb.bkcore.models import ComponentSystem, ESBBuffetComponent
try:
    from esb.management.utils.ee_constants import BUFFET_SYSTEMS, BUFFET_COMPONENTS
except:
    from esb.management.utils.ec_constants import BUFFET_SYSTEMS, BUFFET_COMPONENTS

class Command(BaseCommand):

    def handle(self, *args, **kwargs):
        self.init_buffet_systems()
        self.init_buffet_components()

    def init_buffet_systems(self):
        for system in BUFFET_SYSTEMS:
            system_name = system.pop('name')
            obj, created = ComponentSystem.objects.get_or_create(name=system_name, defaults=system)
            if created:
                print 'add new system [%s] succ' % system_name

    def init_buffet_components(self):
        systems = dict(ComponentSystem.objects.filter(name__in=BUFFET_COMPONENTS.keys()).values_list('name', 'id'))
        for system_name, components in BUFFET_COMPONENTS.iteritems():
            system_id = systems.get(system_name)
            if system_id is None:
                print 'system [%s] not exist, please check config' % system_name
                continue
            for comp in components:
                obj, created = ESBBuffetComponent.objects.update_or_create(system_id=system_id, registed_path=comp.pop('registed_path'), registed_http_method=comp.pop('registed_http_method'), defaults=comp)
                if created:
                    print 'add new buffet components: system=%s, registed_http_method=%s, registed_path=%s' % (
                     system_name, obj.registed_http_method, obj.registed_path)
                else:
                    print 'update buffet component: system=%s, registed_http_method=%s, registed_path=%s' % (
                     system_name, obj.registed_http_method, obj.registed_path)

        return
